package com.kara.woodAgent.agent.wood.node;

import com.kara.woodAgent.agent.graph.Next;
import com.kara.woodAgent.agent.graph.Node;
import com.kara.woodAgent.agent.tool.provider.ToolProvider;
import com.kara.woodAgent.agent.wood.context.WoodReactContext;
import com.kara.woodAgent.agent.wood.playload.InterruptMessage;
import com.kara.woodAgent.agent.wood.playload.InterruptPayload;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.data.message.ToolExecutionResultMessage;

import java.util.List;

/**
 * @author tzy
 * @version 1.0
 * @project wood_agent
 * @description
 * @date 2025/6/11 12:28:49
 */
public class ActionToolNode implements Node<WoodReactContext> {

    private final ToolProvider.ToolServiceHolder holder;


    public ActionToolNode(ToolProvider.ToolServiceHolder holder) {
        this.holder = holder;
    }


    @Override
    public Next execute(WoodReactContext context) {

        if (context.getChannel().checking()) {

            InterruptMessage resume = (InterruptMessage) context.getChannel().resume();
            //完成 interrupt 工具调用
            ToolExecutionResultMessage resultMessage = new ToolExecutionResultMessage(resume.getId(), "interrupt", resume.getContent());
            context.getChatMessages().add(resultMessage);
            context.setToolExecutionRequest(null);


            return Next.NextNode("model").step("完成 interrupt  工具调用");
        } else {

            List<ToolExecutionRequest> toolExecutionRequest = context.getToolExecutionRequest();
            String memoryId = context.getMemoryId();

            List<ToolExecutionResultMessage> resultMessages = holder.executeTool(memoryId, toolExecutionRequest);

            boolean exit = false;
            boolean interrupt = false;
            InterruptPayload payload = null;
            for (ToolExecutionResultMessage resultMessage : resultMessages) {

                if ("interrupt".equals(resultMessage.toolName())) {
                    //检查点 中断
                    interrupt = true;
                    payload = InterruptPayload.of(resultMessage.id(), resultMessage.text());
                } else if ("exit".equals(resultMessage.toolName())) {
                    exit = true;
                    break;
                } else {
                    context.getChatMessages().add(resultMessage);
                }

            }

            if (interrupt) {
                context.getChannel().checkpoint(payload);
            }
            context.setToolExecutionRequest(null);

            String response = toolExecutionRequest + "   " + resultMessages;
            if (exit) {
                return Next.NextNode("summary").step(response);
            } else {
                return Next.NextNode("model").step(response);
            }
        }

    }
}
